﻿#region imports

using System;
using System.Data.Services;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using Codeplex.ODataTFS.Model.Entities;
using Microsoft.Data.Services.Toolkit.Providers;

#endregion

namespace Codeplex.ODataTFS.Model.Providers
{
	public class TFSStreamProvider : EntityUrlReadOnlyStreamProvider
	{
		private readonly ICredentials _credentials;

		public TFSStreamProvider(ICredentials credentials)
		{
			if (credentials != null)
			{
				NetworkCredential incomingCreds = (NetworkCredential) credentials;
				NetworkCredential netCred = new NetworkCredential(incomingCreds.UserName, incomingCreds.Password);
				_credentials = netCred;
			}
		}

		public override Stream GetReadStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
		{
			var streameable = entity as IStreamEntity;
			if (streameable == null)
			{
				return null;
			}

			using (var client = new WebClient {Credentials = this._credentials})
			{
				Uri streamingLoc = streameable.GetUrlForStreaming();
				string credentialsStr = string.Format(
					CultureInfo.InvariantCulture,
					@"{0}:{1}",
					((NetworkCredential) _credentials).UserName,
					((NetworkCredential) _credentials).Password);
				client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(credentialsStr));
				byte[] bytes = client.DownloadData(streamingLoc);
				return new MemoryStream(bytes);
			}
		}

		public override Stream GetWriteStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
		{
			var attachment = entity as Attachment;
			string tempFile = Path.Combine(Path.GetTempPath(), attachment.Id);

			return new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite);
		}

		public override string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
		{
			return entitySetName == "Attachments" ? "Codeplex.ODataTFS.Model.Entities.Attachment" : null;
		}
	}
}
